<?php

namespace App\Models;

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Db;
use Illuminate\Support\Facades\Schema;
use App\Models\Traits\QueryFilters;

class BaseModel extends Model
{
    use QueryFilters;


    //表单相关 ----------------------------------------
    //表单所有设置
    protected $formSet = [];

    //新建时忽略,自动生成不可由用户更改的字段
    protected $ignoreCreate = ['mslug'];

    //修改时忽略
    protected $ignoreUpdate = ['mslug'];

    protected $gridFields = [];
    protected $showFields = [];
    //修改时与新建时设置不一样的，此设置在修改时将替换新建时的设置，如有闭包函数等可直接在addUpdateReplace方法中修改
    protected $updateReplace = [];
    // 枚举设置
    protected $enums = [];

    //模型相关
    protected $modelTitle = '';
    protected $modelModule = '';
    protected $modelSets = [];



    //表单相关 ------------------------------------------------------------
    //$formSet的增强设置方式，将补充或替换$formSet，以防匿名函数等出错
    public function addFormSet(): array
    {
        return [];
    }


    //以防匿名函数等出错时在此设$formUpdateReplace
    public function addUpdateReplace(): array
    {
        return [];
    }

    //未设$formSet时自动生成的$formSet
    public function initFormSet()
    {
        $ignore = array_intersect($this->ignoreCreate, $this->ignoreUpdate);
        $fields = array_diff($this->getTableFields(), $ignore);
        $formSet = [];
        foreach ($fields as $k => $val) {
            if ($val == 'id') {
                $formSet[$val] = [
                    'display' => 'ID'
                ];
            } else {
                $formSet[$val] = [
                    'text' => ucfirst($val)
                ];
            }
        }
        return $formSet;
    }

    //所有设置字段
    public function getFormSet()
    {
        $set = array_merge($this->formSet, $this->addFormSet());
        if (!empty($set)) {
            return $set;
        } else {
            return $this->initFormSet();
        }
    }

    //新建时返回
    public function getFormCreate()
    {
        $fields = array_diff_key($this->getFormSet(), array_flip($this->ignoreCreate));
        return $fields;
    }
    //修改时返回
    public function getFormUpdate()
    {
        $fields = array_merge($this->getFormSet(), $this->updateReplace, $this->addUpdateReplace());
        $fields = array_diff_key($fields, array_flip($this->ignoreUpdate));
        return $fields;
    }


    public function getComments()
    {
        $fields = $this->getFormSet();
        $comments = [];
        foreach ($fields as $key => $value) {
            if (is_numeric($key) || !is_array($value) || empty($value)) continue;
            $comments[$key] = ['type' => key($value), 'title' => array_shift($value)];
        }
        return $comments;
    }

    //后台index时显示字段
    public function getGridFields()
    {
        $comments = $this->getComments();
        $fields = $this->gridFields ?? array_merge($this->getTableFields(), $this->appends);
        $grids = [];
        foreach ($fields as $key => $value) {
            $grids[$value] = empty($comments[$value]) ? ['type' => 'text', 'title' => ucfirst($value)] : $comments[$value];
        }
        return $grids;
    }


    /**
     * 模型表字段
     */
    public function getTableFields($refrech = false)
    {
        $table = $this->getTable();
        if ($refrech || empty(Cache::get('table-fields-' . $table))) {
            $fields = Schema::getColumnListing($table);
            Cache::forever('table-fields-' . $table, $fields);
        } else {
            $fields = Cache::get('table-fields-' . $table);
        }
        return $fields;
    }

    //获取字段详情
    public function getDetailFields($fields = '')
    {
        if ($fields == 'grid') {
            $fields = $this->gridFields ?: $this->getTableFields();
        } elseif ($fields == 'show') {
            $fields = $this->showFields ?: $this->getTableFields();
        } elseif (is_array($fields)) {
            if ($this->getVisible()) {
                $fields = array_intersect($this->getVisible(), $fields);
            } else {
                $all = array_merge($this->getTableFields(), $this->appends);
                $all = array_diff($all, $this->hidden);
                $fields = array_intersect($all, $fields);
            }
        } else {
            return [];
        }
        $comments = $this->getComments();
        foreach ($fields as $key => $value) {
            $result[$value] = empty($comments[$value]) ? ['type' => 'text', 'title' => ucfirst($value)] : $comments[$value];
        }
        return $result;
    }

    public function getEnums()
    {
        return $this->enums ?? [];
    }

    public function getModelSets()
    {
        return $this->modelSets ?? [];
    }

    public function getModelTitle()
    {
        return $this->modelTitle ?? '';
    }
    public function getModelModule()
    {
        return $this->modelModule ?? '';
    }
}


/**
 * 参考 model初始设置
 * protected:
 *  $connection, $table,$primaryKey = 'id',$keyType = 'int',$with = [],$withCount = [],$perPage = 15,
 *  $attributes = [],$original = [],$changes = [], $casts = [],$dates = [],$dateFormat(string),$appends = [],
 *  $relations = [],$touches = []联动更新关系,
 *  $fillable = [],$guarded = ['*'],
 *  $hidden = [],$visible = [],
 *  $dispatchesEvents = [],$observables = [],
 * 
 * public
 *  $exists = false,$wasRecentlyCreated = false,$incrementing = true,
 *  $snakeAttributes = true,$timestamps = true,
 * 
 * protected static
 *  $resolver,$dispatcher,$booted = [],$traitInitializers = [],
 *  $globalScopes = [],$ignoreOnTouch = [],$mutatorCache = [],
 *  $unguarded = false,
 * 
 * const
 *  CREATED_AT = 'created_at',UPDATED_AT = 'updated_at',   
 */
